package com.java.mall_imooc.controller;

import com.java.mall_imooc.common.utils.PageUtils;
import com.java.mall_imooc.common.utils.R;
import com.java.mall_imooc.entity.Category;
import com.java.mall_imooc.service.CategoryService;
import com.java.mall_imooc.vo.CategoryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Set;


/**
 * 商品类目表
 *
 * @author jl
 * @since 2020-03-16 13:31:58
 */
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    /**
     * 获取商品类目的树形结构数据
     */
    @GetMapping("/tree")
    public R<List<CategoryVo>> categoryTree() {
        List<CategoryVo> categoryVo = categoryService.categoryTree();
        return R.ok(categoryVo);
    }

    /**
     * 根据parentId查询所有子类目id
     */
    @GetMapping("/subCategoryIds")
    public R<Set<Integer>> subCategoryIds(@RequestParam("parentId")Integer parentId) {
        return R.ok(categoryService.subCategoryIds(parentId));
    }

    /**
     * 分页查询category
     * 当前页码page、每页显示记录数limit
     */
    @GetMapping("/list")
    public R list(Category category, @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum, @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize) {
        if (pageNum < 1) pageNum = 1;
        if (pageSize > 100) pageSize = 100;
        PageUtils page = categoryService.queryPage(category, pageNum, pageSize);

	    return R.ok(page);
    }


    /**
     * 根据主键查询category
     */
    @GetMapping("/info/{id}")
    public R info(@PathVariable("id") Integer id){
		Category category = categoryService.getById(id);

        return R.ok(category);
    }

    /**
     * 新增category
     */
    @PostMapping("/save")
    public R save(@RequestBody Category category){
		categoryService.save(category);

        return R.ok();
    }

    /**
     * 修改category
     */
    @PutMapping("/update")
    public R update(@RequestBody Category category){
		categoryService.updateById(category);

        return R.ok();
    }

    /**
     * 删除category
     */
    @DeleteMapping("/delete")
    public R delete(@RequestBody Integer[] ids){
		categoryService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

}
